<template>
    <div
        class="sticky top-[5rem]  w-full p-5 bg-white border border-gray-200 rounded-lg dark:bg-stone-950 dark:border-gray-700">

        <!-- 目录标题 -->
        <h2 class="flex items-center mb-2 font-bold text-gray-900 uppercase dark:text-white">
            <!-- 目录图标 -->
            <svg-icon name="Toc" class="icon w-3.5 h-3.5 mr-2"></svg-icon>
            文章目录
        </h2>

        <div ref="scrollbar" class=" overflow-y-auto max-h-screen border-l-2 border-gray-200">
            <MdCatalog id="MdCatalog" :editor-id="articleEditorId" :scrollElement="scrollElement"
                :theme="articleEditorTheme" />
        </div>
    </div>
</template>

<script setup>
import { MdCatalog } from 'md-editor-v3'
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { useDark } from '@vueuse/core'
import { throttle } from 'lodash' // 引入lodash的throttle函数


const scrollElement = document.documentElement
const articleEditorId = "articleContent"
const isDark = useDark()
const articleEditorTheme = isDark.value ? 'dark' : 'light'
const scrollbar = ref(null)

onMounted(() => {
    window.addEventListener('scroll', throttledHandleContentScroll);
})

// 处理窗口滚动事件
function handleContentScroll() {
    // 如果目录没有高度，则不处理
    if (scrollbar.value.scrollHeight == 0) return;
    console.log('窗口滚动事件');
    // 窗口当前的滚动位置
    let scrollY = window.scrollY
    // 获取目录的顶部位置信息
    const tocTopY = scrollbar.value.getBoundingClientRect().top
    const windowHeight = window.innerHeight
    const windowscrollHeight = scrollElement.scrollHeight
    // 计算窗口滚动比例，让目录等比滚动
    const scrollRatio = (scrollY - tocTopY) / (windowscrollHeight - windowHeight);
    // 滚动比例*（滚动条的总高度-可见高度）。
    scrollbar.value.scrollTop = scrollRatio * (scrollbar.value.scrollHeight - scrollbar.value.clientHeight);
}
// 创建节流防抖后的滚动事件处理函数
const throttledHandleContentScroll = throttle(handleContentScroll, 100);

// 移除窗口滚动监听
onBeforeUnmount(() => window.removeEventListener('scroll', throttledHandleContentScroll))


</script>

<style scoped>
.max-h-screen {
    max-height: 75vh;
}


.overflow-y-auto {
    overflow-x: hidden;
}

/* 滚动条整体样式 */
::-webkit-scrollbar {

    width: 2px;
    /* 设置滚动条宽度 */
}

/* 鼠标悬停时滚动条变粗 */
:hover ::-webkit-scrollbar {
    width: 8px;
    /* 设置滚动条宽度 */
}

/* 滚动条滑块样式 */
::-webkit-scrollbar-thumb {
    border-radius: 5px;
    /* 设置滑块的圆角 */
    background: rgba(62, 14, 174, 0.2);
    /* 设置滑块的背景颜色 */
}


/* 滚动条轨道样式 */
::-webkit-scrollbar-track {
    border-radius: 0;
    /* 设置轨道的圆角 */
    background: rgba(0, 0, 0, 0.1);
    /* 设置轨道的背景颜色 */
}
</style>